package com.xiaoyun.ui;

import javax.swing.JPanel;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.JTabbedPane;
import java.awt.Insets;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.JComboBox;
import javax.swing.table.DefaultTableModel;
import com.xiaoyun.dao.JDBCDAO;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.DefaultComboBoxModel;
import com.xiaoyun.util.*;

public class MemberMsgPanel extends JPanel {
	private JPanel panel_1;
	private GridBagConstraints gbc_panel_1;
	private JTextField tfSearch;
	private JTextField tfAccount;
	private JTextField tfName;
	private JTextField tfPassword;
	private JTextField tfTel;
	private JTextField tfEmail;
	private JTextField tfPage;
	private JScrollPane scrollPane;
	private DefaultTableModel dtable;
	private JButton btnAdd;
	private JButton btnDelete;
	private JButton btnFix;
	private JTable table;
	private JComboBox cbSex;
	private JComboBox cbType;
	private JLabel labelNow;
	private JLabel labelAll;
	private JLabel message;
	private JDBCDAO jdao;
	private ArrayList<Integer> arraylist;
	private int startLine,endLine,count,pageNow;
	private String sqlMain;
	private String sqlLike;
	private String sqlGetNum;
	private Object[][] obj;
	private Object[] column = {"账号","姓名","性别","密码","等级","手机","邮箱","注册时间"};
	/**
	 * Create the panel.
	 */
	public MemberMsgPanel() {
		init();
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{0, 0};
		gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0};
		gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
		setLayout(gridBagLayout);
		
		JPanel panel = new JPanel();
		GridBagConstraints gbc_panel = new GridBagConstraints();
		gbc_panel.insets = new Insets(0, 0, 5, 0);
		gbc_panel.fill = GridBagConstraints.BOTH;
		gbc_panel.gridx = 0;
		gbc_panel.gridy = 0;
		add(panel, gbc_panel);
		
		btnAdd = new JButton("添加员工");
		btnAdd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				tfName.setText("");
				tfPassword.setText("");
				tfTel.setText("");
				tfEmail.setText("");
				cbSex.setSelectedIndex(0);
				cbType.setSelectedIndex(2);
				labelEmpty();
				if(btnAdd.getText().equals("添加员工")){
					String sql ="select account as account from xy_member where rownum=1 order by account desc";
					HashMap haspMap = new HashMap();
					haspMap = jdao.findOne(sql, new Object[]{});
					int account = Integer.valueOf(String.valueOf(haspMap.get("account")));
					tfAccount.setText(""+(account+1));
					tfAccount.setEnabled(false);
					panel_1.setVisible(true);
					btnAdd.setText("取消");
					return;
				}
				if(btnAdd.getText().equals("收回")){
					showTable();
					panel_1.setVisible(false);
					btnAdd.setText("取消");
					return;
				}
				btnAdd.setText("添加员工");
				panel_1.setVisible(false);
			}
		});
		panel.add(btnAdd);
		
		JButton btnConfire = new JButton("确定");
		btnConfire.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				labelEmpty();
				String sql = "insert into xy_member (account,name,sex,password,type,email,tel,time) values (?,?,?,?,?,?,?,?)";
				int i=0;
				long ac=0;
				if(!tfPassword.getText().matches(VAR.matchPassword)){
					message.setText("密码为6位字母或数字");
					return;
				}
				if(!tfTel.getText().matches(VAR.matchTel)){
					message.setText("手机格式错误");
					return;
				}
				if(!tfEmail.getText().matches(VAR.matchEmail)){
					message.setText("邮箱格式错误");
					return;
				}
				i = jdao.update(sql, new Object[]{tfAccount.getText(),tfName.getText(),cbSex.getSelectedItem().toString(),tfPassword.getText(),Integer.parseInt(cbType.getSelectedItem().toString()),tfEmail.getText(),tfTel.getText(),new Date(System.currentTimeMillis())});
				if(i==1){
					message.setText("用户添加成功");
					btnAdd.setText("收回");
					return;
				}else{
					message.setText("数据库连接异常");
					return;
				}
			}
		});
		
		btnDelete = new JButton("删除员工");
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(btnDelete.getText().equals("删除员工")){
					table.setEnabled(true);
					btnDelete.setText("选择");
				}else {
					int row = table.getSelectedRow(),k=0;
					String sql = "delete from xy_member where account = ?";
					Object account =  table.getValueAt(row, 0);
					k=jdao.update(sql, new Object[]{account});
					if(k==1){
						showTable();
						table.setEnabled(false);
						btnDelete.setText("删除员工");
					}else{
						message.setText("数据库连接异常");
						table.setEnabled(false);
						btnDelete.setText("删除员工");
					}
				}
			}
		});
		panel.add(btnDelete);
		
		btnFix = new JButton("编辑员工");
		btnFix.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(btnFix.getText().equals("编辑员工")){
					arraylist.clear();
					table.setEnabled(true);
					btnFix.setText("保存");
				}else{
					int len = arraylist.size();
					System.out.println(""+len);
					int k=0;
					String errorMes="";
					String sql = "update xy_member set name=? ,sex=? ,password=? ,type=? ,tel=? ,email=? where account=?";
					for(int i=0;i<len;i++){
						int row = arraylist.get(i);
						table.repaint();
						//dtable.getValueAt(row, 2);
						Object account =  table.getValueAt(row, 0);
						Object name = table.getValueAt(row, 1);
						Object sex = dtable.getValueAt(row, 2);
						Object password = table.getValueAt(row, 3);
						Object type = table.getValueAt(row, 4);
						Object tel = table.getValueAt(row, 5);
						Object email = table.getValueAt(row, 6);
						System.out.println(""+row+account+len+name+sex+email);
						if(!email.toString().matches(VAR.matchEmail)){
							errorMes=errorMes+account+",";
							continue;
						}
						if(!password.toString().matches(VAR.matchPassword)){
							errorMes=errorMes+account+",";
							continue;
						}
						if(!tel.toString().matches(VAR.matchTel)){
							errorMes=errorMes+account+",";
							continue;
						}
						if(!(sex.toString().equals("男")|sex.toString().equals("女"))){
							errorMes=errorMes+account+",";
							continue;
						}
						if(!(type.toString().equals("1")|type.toString().equals("2")|type.toString().equals("3"))){
							errorMes=errorMes+account+",";
							continue;
						}
						try {
							k=jdao.update(sql, new Object[]{name.toString(),sex.toString(),password.toString(),Integer.parseInt(type.toString()),Long.parseLong(tel.toString()),email.toString(),Integer.parseInt(account.toString())});
						//	System.err.println(k+"k-----");
						} catch (Exception e2) {
							e2.printStackTrace();
						}
						if(k!=1){
							errorMes=errorMes+account+",";
						}
					}
					if(errorMes.equals("")){
						message.setText("修改成功");
					}else{
						message.setText(message+"信息格式有错");
					}
					table.setEnabled(false);
					btnFix.setText("编辑员工");
				}
			}
		});
		panel.add(btnFix);
		
		tfSearch = new JTextField();
		panel.add(tfSearch);
		tfSearch.setColumns(10);
		
		JButton btnSearch = new JButton("搜索");
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				labelEmpty();
				String search = "%"+tfSearch.getText()+"%";
				shouLikeTable(search);
			}
		});
		panel.add(btnSearch);
		
		message = new JLabel("");
		panel.add(message);
		
		
		gbc_panel_1 = new GridBagConstraints();
		gbc_panel_1.insets = new Insets(0, 0, 5, 0);
		gbc_panel_1.fill = GridBagConstraints.BOTH;
		gbc_panel_1.gridx = 0;
		gbc_panel_1.gridy = 1;
		add(panel_1, gbc_panel_1);
		panel_1.setVisible(false);
		
		JLabel label = new JLabel("账号");
		panel_1.add(label);
		
		tfAccount = new JTextField();
		panel_1.add(tfAccount);
		tfAccount.setColumns(10);
		
		JLabel lblNewLabel = new JLabel("姓名");
		panel_1.add(lblNewLabel);
		
		tfName = new JTextField();
		panel_1.add(tfName);
		tfName.setColumns(10);
		
		JLabel label_3 = new JLabel("性别");
		panel_1.add(label_3);
		
		cbSex = new JComboBox();
		cbSex.setModel(new DefaultComboBoxModel(new String[] {"男", "女"}));
		panel_1.add(cbSex);
		
		JLabel label_1 = new JLabel("密码");
		panel_1.add(label_1);
		
		tfPassword = new JTextField();
		panel_1.add(tfPassword);
		tfPassword.setColumns(10);
		
		JLabel label_2 = new JLabel("等级");
		panel_1.add(label_2);
		
		cbType = new JComboBox();
		cbType.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
		panel_1.add(cbType);
		
		JLabel label_4 = new JLabel("手机");
		panel_1.add(label_4);
		
		tfTel = new JTextField();
		panel_1.add(tfTel);
		tfTel.setColumns(10);
		
		JLabel label_5 = new JLabel("邮箱");
		panel_1.add(label_5);
		
		tfEmail = new JTextField();
		panel_1.add(tfEmail);
		tfEmail.setColumns(10);
		
		panel_1.add(btnConfire);
		
		scrollPane = new JScrollPane();
		GridBagConstraints gbc_scrollPane = new GridBagConstraints();
		gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
		gbc_scrollPane.fill = GridBagConstraints.BOTH;
		gbc_scrollPane.gridx = 0;
		gbc_scrollPane.gridy = 2;
		add(scrollPane, gbc_scrollPane);
		
		JPanel panel_2 = new JPanel();
		GridBagConstraints gbc_panel_2 = new GridBagConstraints();
		gbc_panel_2.fill = GridBagConstraints.BOTH;
		gbc_panel_2.gridx = 0;
		gbc_panel_2.gridy = 3;
		add(panel_2, gbc_panel_2);
		
		JButton btnBefore = new JButton("上一页");
		btnBefore.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				labelEmpty();
				if(startLine<16){
					return;
				}
				pageNow--;
				showPageNum(pageNow,(count/16+1));
				startLine-=16;
				showTable();
			}
		});
		panel_2.add(btnBefore);
		
		JButton btnNext = new JButton("下一页");
		btnNext.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				labelEmpty();
				if(startLine>count-16){
					return;
				}
				pageNow++;
				showPageNum(pageNow,(count/16+1));
				startLine+=16;
				showTable();
			}
		});
		panel_2.add(btnNext);
		
		JButton btnJump = new JButton("跳转");
		btnJump.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				labelEmpty();
				int jumpNum=0;
				String str = tfPage.getText();
				try {
					jumpNum = Integer.valueOf(str);
				} catch (Exception e2) {
					message.setText("请输入数字");
					return;
				}
				if(jumpNum>(count/16+1)){
					message.setText("不能超过总页数"+(count/16+1));
					return;
				}
				if(jumpNum<1){
					message.setText("不能小于1");
					return;
				}
				pageNow=jumpNum;
				startLine = 16*(jumpNum-1);
				showPageNum(pageNow,(count/16+1));
				showTable();
			}
		});
		
		tfPage = new JTextField();
		panel_2.add(tfPage);
		tfPage.setColumns(10);
		panel_2.add(btnJump);
		
		labelNow = new JLabel("第几页");
		panel_2.add(labelNow);
		
		labelAll = new JLabel("一共几页");
		panel_2.add(labelAll);

		table.addMouseListener(new MouseListener() {
			
			public void mouseReleased(MouseEvent arg0) {
				// TODO Auto-generated method stub
				int row = table.getSelectedColumn();//那一行
				int column = table.getSelectedColumn(); //那一列
				if(table.isEnabled()){
					table.setValueAt(table.getValueAt(row, column), row, column);
				}
			}
			
			public void mousePressed(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			public void mouseExited(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			public void mouseEntered(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			public void mouseClicked(MouseEvent arg0) {
				// TODO Auto-generated method stub
				if(!arraylist.contains(table.getSelectedRow())){
					arraylist.add(table.getSelectedRow());
				}
				if(btnDelete.getText().equals("选择")){
					btnDelete.setText("确定");
				}
			}
		});
		showPageNum(pageNow,(count/15+1));
		System.out.println(count);
		showTable();
	}

	private void init() {
		// TODO Auto-generated method stub
		panel_1 = new JPanel();
		scrollPane = new JScrollPane();
		labelNow = new JLabel();
		labelAll= new JLabel();
		table = new JTable();
		table.setEnabled(false);
		jdao = new JDBCDAO();
		obj = null;     //前面不加*号是因为后面有rownum会增加一列。
		sqlMain = "select account,name,sex,password,type,tel,email,time from (select rownum rn,account,name,sex,password,type,tel,email,time from xy_member where rownum<?) where rn >?";
		sqlLike = "select account,name,sex,password,type,tel,email,time from xy_member where account like ? or name like ?";
		sqlGetNum = "select count(account) as account from xy_member where 1=1";
		arraylist = new ArrayList<Integer>();
		startLine = 0;
		count=0;
		pageNow=1;
	}

	public void shouLikeTable(String str){
		table.removeAll();
		try {
			obj = jdao.ArrayListToArray(jdao.findAll(sqlLike, new Object[]{str,str},8));
			showTableInit();
		} catch (Exception e) {
			message.setText("没有该用户");
		}
	}
	public void showTable(){
		table.removeAll();
		obj = jdao.ArrayListToArray(jdao.findAll(sqlMain, new Object[]{startLine+17,startLine},8));//之前sql第二个参数是showLine+15，错误。第二个参数是显示的行数。
		showTableInit();
		showPageNum(pageNow,(count/16+1));
	}
	
	public void showTableInit(){
		HashMap haspMap = new HashMap();
		haspMap = jdao.findOne(sqlGetNum, new Object[]{});
		count = Integer.valueOf(String.valueOf(haspMap.get("account")));
		//System.out.println("---------"+count);
		dtable = new DefaultTableModel(obj,column){        //因为账号的唯一性，规定账号不能修改。
			public boolean isCellEditable(int row,int column){
				if(column==0||column==7){
					return false;
				}else{
					return true;	
				}		
			}
		};
		dtable.setRowCount(16);
		table.setAutoResizeMode(table.AUTO_RESIZE_ALL_COLUMNS);
		table.setRowHeight(30);
		table.setPreferredScrollableViewportSize(new Dimension(600,330));
		table.setModel(dtable);
		scrollPane.setViewportView(table);
	}
	public void showPageNum(int now,int all){
		labelNow.setText("第"+now+"页");
		labelAll.setText("一共"+all+"页");
	}
	public void labelEmpty(){
		message.setText("");
		//labelError.setText("");
	}
	public void testEmpty(){
		
	}
}
